package camid.distribution.lifecycle.perclient;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import camid.distribution.activeobject.ObjectRegistry;

public class LeasingAgent implements Runnable{

//	private ObjectRegistry registry;
//	private Map<String, Lease> leaseMap;
	private AtomicInteger flag;
	
	public LeasingAgent(ObjectRegistry registry, Map<String, Lease> leaseMap) {
//		this.registry = registry;
//		this.leaseMap = leaseMap;
		this.flag = new AtomicInteger(0);
	}

	private PerClientLifecycleManager pclm;
	
	
	public LeasingAgent(PerClientLifecycleManager perClientLifecycleManager) {
		this.pclm = perClientLifecycleManager;
		this.flag = new AtomicInteger(0);
	}

	@Override
	public void run() 
	{
		while(flag.get() == 0)
		{
			List<String> objectIds = this.pclm.getLeasedObjectIds();
			for(String id : objectIds)
			{
				Lease lease = pclm.getLease(id);
				if(lease == null || !lease.isValid())
				{
					pclm.destroyObject(id);
				}
			}
		}
		
	}

	public void shutdown() 
	{
		flag.set(1);
	}

}
